﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ninject;
using Legazpi.Payroll.BusinessLogic.Services.Interfaces;
using Legazpi.Payroll.DataAccess.DataObjects;
using Web.Codes;
using System.Globalization;
using Web.Utils;

namespace Legazpi.Payroll.Web.Admin.Payroll
{
    public partial class InitPayPeriod : System.Web.UI.Page
    {
        [Inject]
        public IPayrollDateService _payrollDateService { get; set; }

        public bool IsSuccess { get; set; }
        public bool IsValidSave { get; set; }
        public string NotifyText { get; set; }
        private DateTime InvalidDate = new DateTime(1900, 1, 1);

        private int _payDateId;
        public int CurrentPayDateId
        {
            get
            {
                int id;
                return int.TryParse(PaydateId.Value, out id) ? id : 0;
            }
            set 
            {
                _payDateId = value;
                PaydateId.Value = _payDateId.ToString();
            }
        }

        #region Implementations
        void BindGrid()
        {
            repeater.DataSource = _payrollDateService.GetAll();
            repeater.DataBind();
        }
        void Delete(int id)
        {
            _payrollDateService.Delete(id);
            IsSuccess = _payrollDateService.Save();
            if (IsSuccess)
            {
                NotifyText = "Successfully Deleted.";
                BindGrid();
            }
            else
            {
                IsValidSave = false;
                NotifyText = "Error Deleting record. cannot delete record with dependency";            
            }                
        }

        void Edit(int id)
        {
            var payDate = _payrollDateService.GetById(id);
            if (payDate == null)
                return;

            MonthDroplistStart.ClearSelection();
            MonthDroplistEnd.ClearSelection();
            DayDroplistStart.ClearSelection();
            DayDroplistEnd.ClearSelection();
            YearDroplistStart.ClearSelection();
            YearDroplistEnd.ClearSelection();

            ObjectToData(payDate);

            CurrentPayDateId = payDate.Id;
            SubmitBtn.Text = "Update";
        }

        void Update(int id)
        {
            var payDate = _payrollDateService.GetById(id);
            if (payDate == null)
            {
                Add();
                return;
            }
            DataToObject(ref payDate);

            if (IsValidSave)
            {
                _payrollDateService.Update(payDate);
                if (!payDate.Active && SetActiveChckbox.Checked)
                    _payrollDateService.SetActive(payDate.Id);

                IsSuccess = _payrollDateService.Save();

                NotifyText = "Successfully Updated Record.";            
            }
            else
                NotifyText = "Found Error while updating record, please check values before submitting.";
        }
        void Add()
        {
            var payDate = new PayrollDate();

            DataToObject(ref payDate);

            if (IsValidSave)
            {
                _payrollDateService.Add(payDate);
                IsSuccess = _payrollDateService.Save();
                if (!payDate.Active && SetActiveChckbox.Checked)
                {
                    _payrollDateService.SetActive(payDate.Id);
                    _payrollDateService.Save();
                }
                    
                CurrentPayDateId = payDate.Id;
                NotifyText = "Successfully Added New Record.";
                SubmitBtn.Text = "Update";
            }
            else
                NotifyText = "Found Error while updating record, please check values before submitting.";

        }
        void ClearForm()
        {            
            CurrentPayDateId = 0;
            SubmitBtn.Text = "Submit";
        }

        void Save()
        {
            if (CurrentPayDateId == 0)
                Add();
            else
                Update(CurrentPayDateId);
        }
        void DataToObject(ref PayrollDate obj)
        {
            int tempInt;
            int moStart = int.TryParse(MonthDroplistStart.SelectedValue, out tempInt) ? tempInt : 1;
            int dayStart = int.TryParse(DayDroplistStart.SelectedValue, out tempInt) ? tempInt : 1;
            int yearStart = int.TryParse(YearDroplistStart.SelectedValue, out tempInt) ? tempInt : 1900;
            int moEnd = int.TryParse(MonthDroplistEnd.SelectedValue, out tempInt) ? tempInt : 1;
            int dayEnd = int.TryParse(DayDroplistEnd.SelectedValue, out tempInt) ? tempInt : 1;
            int yearEnd = int.TryParse(YearDroplistEnd.SelectedValue, out tempInt) ? tempInt : 1900;

            try
            {
                var _startDate = new DateTime(yearStart, moStart, dayStart);
                var _endDate = new DateTime(yearEnd, moEnd, dayEnd);

                if (_startDate == null || _endDate == null)
                {
                    IsValidSave = false;
                    return;
                }

                IsValidSave = (!_startDate.Equals(InvalidDate) && !_endDate.Equals(InvalidDate));
                IsValidSave = moStart == moEnd;
                IsValidSave = yearStart == yearEnd;

                if (dayStart == 1)
                    IsValidSave = dayEnd == 15;
                else if (dayStart == 16)
                    IsValidSave = dayEnd > dayStart;

                if (IsValidSave)
                {
                    obj.Paydate = _startDate;
                    obj.Startdate = _startDate;
                    obj.Enddate = _endDate;                    
                }
            }
            catch { }

        }

        void ObjectToData(PayrollDate obj)
        {
            //Start Date
            var moStartItem = MonthDroplistStart.Items.FindByValue(obj.Startdate.Month.ToString("00"));
            if (moStartItem != null)
                moStartItem.Selected = true;
            var dayStartItem = DayDroplistStart.Items.FindByValue(obj.Startdate.Day.ToString("00"));
            if (dayStartItem != null)
                dayStartItem.Selected = true;
            var yearStartItem = YearDroplistStart.Items.FindByValue(obj.Startdate.Year.ToString());
            if (yearStartItem != null)
                yearStartItem.Selected = true;

            //End Date
            var moEndItem = MonthDroplistEnd.Items.FindByValue(obj.Enddate.Month.ToString("00"));
            if (moEndItem != null)
                moEndItem.Selected = true;
            var dayEndItem = DayDroplistEnd.Items.FindByValue(obj.Enddate.Day.ToString("00"));
            if (dayEndItem != null)
                dayEndItem.Selected = true;
            var yearEndItem = YearDroplistEnd.Items.FindByValue(obj.Enddate.Year.ToString());
            if (yearEndItem != null)
                yearEndItem.Selected = true;

            SetActiveChckbox.Checked = obj.Active;
        }
        void BindMonthDropdown(DropDownList month)
        {
            for (int i = 0; i < 12; i++)
            {
                var iMonth = i + 1;
                month.Items.Add(new ListItem
                {
                    Value = iMonth.ToString("00"),
                    Text = CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[i].Substring(0, 3),
                    Selected = (iMonth == DateTime.Now.Month)
                });

            }
        }
        void BindYearDropdown(DropDownList year)
        {
            for (int i = DateTime.Now.Year - 2; i < DateTime.Now.Year + 2; i++)
            {
                year.Items.Add(new ListItem
                {
                    Value = i.ToString(),
                    Text = i.ToString(),
                    Selected = (i == DateTime.Now.Year)
                });
            }
        }

        void LoadPayrollStatus()
        {
            var currentActivePayroll = _payrollDateService.GetActivePayroll();
            var previousPayroll = _payrollDateService.GetPreviousPayroll();
            if (currentActivePayroll != null)
                CurrentActivePayrollLiteral.Text = string.Format("{0} - {1}",
                    DateTimeHelper.FormatDateString(currentActivePayroll.Startdate),
                    DateTimeHelper.FormatDateString(currentActivePayroll.Enddate));

            if (previousPayroll != null)
            PreviousPayrollLiteral.Text = string.Format("{0} - {1}",
                DateTimeHelper.FormatDateString(previousPayroll.Startdate),
                DateTimeHelper.FormatDateString(previousPayroll.Enddate));        
        }
        void SetPaydateAsActive(int id)
        {
            _payrollDateService.SetActive(id);
            _payrollDateService.Save();
            BindGrid();
            LoadPayrollStatus();
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGrid();
                BindMonthDropdown(MonthDroplistStart);
                BindMonthDropdown(MonthDroplistEnd);
                BindYearDropdown(YearDroplistStart);
                BindYearDropdown(YearDroplistEnd);
                LoadPayrollStatus();
            }
                
        }

        protected void repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int intTemp = 0;
            if (int.TryParse((string)e.CommandArgument, out intTemp))
            {
                switch (e.CommandName.ToLower())
                {
                    case Constants.Update_Command:
                        Edit(intTemp);
                        break;
                    case Constants.Delete_Command:
                        Delete(intTemp);
                        break;
                    case Constants.Save_Command:
                        SetPaydateAsActive(intTemp);                        
                        break;
                }
            }
        }

        protected void SubmitBtn_Click(object sender, EventArgs e)
        {
            Save();
            if (IsSuccess)
            {
                ClearForm();
                BindGrid();
                LoadPayrollStatus();
            }
        }

        protected void CancelBtn_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var startDateLiteral = (Literal)e.Item.FindControl("StartDateLiteral");
                var endDateLiteral = (Literal)e.Item.FindControl("EndDateLiteral");
                var activeLiteral = (Literal)e.Item.FindControl("ActiveLiteral");
                
                var payDateItem = (PayrollDate)e.Item.DataItem;

                startDateLiteral.Text = DateTimeHelper.FormatDateString(payDateItem.Startdate);
                endDateLiteral.Text = DateTimeHelper.FormatDateString(payDateItem.Enddate);
                activeLiteral.Text = payDateItem.Active ? "Active" : string.Empty;
            }
        }

    }
}